#include "recbox.h"
#include "ui_recbox.h"

#include "recboxitem.h"

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(1),
    col(4)
{
    ui->setupUi(this);

    //在recListUpLayout（水平布局管理器上） 添加一个 RecBoxItem
//    RecBoxItem* item = new RecBoxItem();
//    ui->recListUpLayout->addWidget(item);
}



RecBox::~RecBox()
{
    delete ui;
}


void RecBox::initRecBoxUi(QJsonArray data, int row)
{

    if(row == 2)
    {

        this->row = row;
//        qDebug() << this->row;
        this->col = 8; // 为什么要给成8呢
    }
    else
    {
        //因为qqmusic下面的musicRecBox 和 supplyRecBox可能要保持同步，可能列会影响
        //this->col = 8;
        ui->recListDown->hide(); //如果只有一行，把RecBox的down给隐藏
    }

    imageList = data;

    currentIndex = 0;
    count = imageList.size() / col;

    //在RecBox控件中添加RecBoxItem
    createRecBoxItem();
}



void RecBox::createRecBoxItem()
{
    //删除recListUp内部之间的元素
    QList<RecBoxItem*> recUpList =  ui->recListUp->findChildren<RecBoxItem*>();
    for(auto e : recUpList)
    {
        ui->recListUpLayout->removeWidget(e);
        delete e;
    }

    //删除recListDown内部之间的元素
    QList<RecBoxItem*> recDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for(auto e : recDownList)
    {
        ui->recListDownLayout->removeWidget(e);
        delete e;
    }

    //创建RecBoxItem对象， 往RecBox中添加
    //今日为你推荐的下方的RecBox的行是 1， 列是4
    //但是音乐补给站：row = 2, col = 8

    //qDebug() << col;
    //qDebug() <<
    int index = 0;
    for(int i = currentIndex * col; i < col + currentIndex * col; i++)
    {
        RecBoxItem* item = new RecBoxItem();

        //设置音乐图片与对应的文本
        QJsonObject obj = imageList[i].toObject();
        item->setRecText(obj.value("text").toString());
        item->setRecImage(obj.value("path").toString());


        if( index >= col/2 && 2 == row)
        {
           // qDebug() << obj.value("path").toString() << "=============" << index << "   " << col;
           // ui->recListUpLayout->addWidget(item);
            // void addWidget(QWidget *, int stretch = 0, Qt::Alignment alignment = Qt::Alignment());
            // addWidget就是用来添加控件的
            ui->recListDownLayout->addWidget(item); //这个recListDownLayout  recListUpLayout都是水平布局
        }
        else
        {
             ui->recListUpLayout->addWidget(item);
          //   qDebug() << obj.value("path").toString()  << "-------------" << index << "   " << col;
        }

        index++;
    }
}



void RecBox::on_btDown_clicked()
{
    // 点击之后，需要显示下一组图片
    currentIndex++;
    if(currentIndex >= count)
         currentIndex = 0;

    createRecBoxItem();
}


void RecBox::on_btUp_clicked()
{
    //点击之后，需要显示前一组图片，如果已经是第0组图片，让其显示最后一组图片
    currentIndex--;
    if(currentIndex < 0)
    {
        currentIndex = count - 1;
    }

    createRecBoxItem();
}

